﻿/*
    Copyright (C) 2008, wj2929, wj2929@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Collections.Specialized;

namespace mjRegister
{
    public class Common
    {
        public static string[] PicExt = new string[8] {".jpe",".jpeg",".jpg",".png",".tif",".tiff",".bmp",".gif" };

        public static string utf8(string utf8code)
        {
            return HttpUtility.UrlDecode(Regex.Unescape(utf8code), Encoding.UTF8);
        }

        public static string FilterHtml(string html)
        {
            string re = "<[^>]+>";
            return Regex.Replace(html, re, string.Empty);
        }

        public static string UrlEncode(string html)
        {
            return HttpUtility.UrlEncode(html);
        }

        public static string GetConfigPath()
        {
            return Path.Combine(GetExeDirectory(), "config");
        }

        public static string GetExeDirectory()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        public static int GetInteger(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return -1;
            }
            int id;
            if (int.TryParse(str, out id))
            {
                return id;
            }
            return -1;
        }


        public static string GetMasterTemplateFile()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mastertemplate.ini");
        }

        public static string GetChildTemplateFile()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "childtemplate.ini");
        }

        public static string GetIniPath()
        {
            string iniPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ini");
            if (!Directory.Exists(iniPath))
                Directory.CreateDirectory(iniPath);
            return iniPath;
        }

        public static string GetAddFriendsPath()
        {
            string addFriendsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddFriends");
            if (!Directory.Exists(addFriendsPath))
                Directory.CreateDirectory(addFriendsPath);
            return addFriendsPath; 
        }

        public static void FillDropDownList(ComboBox ddl, Type enumtype)
        {
            if (ddl != null && enumtype.IsEnum)
            {
                string[] names = Enum.GetNames(enumtype);
                Array values = Enum.GetValues(enumtype);
                for (int i = 0; i < names.GetLength(0); i++)
                {
                    ddl.Items.Add(names[i]);
                }
            }
        }

        public static string SerializeObject(object o)
        {
            System.Runtime.Serialization.IFormatter obj = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            MemoryStream ms = new MemoryStream();
            obj.Serialize(ms, o);

            BinaryReader br = new BinaryReader(ms);
            ms.Position = 0;
            byte[] bs = br.ReadBytes((int)ms.Length);
            ms.Close();
            return Convert.ToBase64String(bs);
        }

        public static object DeserializeObject(string str)
        {
            System.Runtime.Serialization.IFormatter obj = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            byte[] bs = Convert.FromBase64String(str);
            MemoryStream ms = new MemoryStream();
            ms.Write(bs, 0, bs.Length);
            ms.Position = 0;
            object o = obj.Deserialize(ms);
            ms.Close();
            return o;
        }


        public static IList<string> GetPicFileNameFromFolder(string folder)
        {
            IList<string> picFileName = new List<string>();

            foreach (string file in Directory.GetFiles(folder))
            {
                if(PicExt.Contains(Path.GetExtension(file)))
                    picFileName.Add(file);
            }

            return picFileName;
        }

        public static string UploadFileEx(string uploadfile, string url,
            string fileFormName, string contenttype, NameValueCollection querystring,
            CookieContainer cookies)
        {
            if ((fileFormName == null) ||
                (fileFormName.Length == 0))
            {
                fileFormName = "file";
            }

            if ((contenttype == null) ||
                (contenttype.Length == 0))
            {
                contenttype = "application/octet-stream";
            }


            string postdata;
            postdata = "?";
            if (querystring != null)
            {
                foreach (string key in querystring.Keys)
                {
                    postdata += key + "=" + querystring.Get(key) + "&";
                }
            }
            Uri uri = new Uri(url + postdata);


            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
            webrequest.CookieContainer = cookies;
            webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webrequest.Method = "POST";


            // Build up the post message header
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append(fileFormName);
            sb.Append("\"; filename=\"");
            sb.Append(Path.GetFileName(uploadfile));
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append(contenttype);
            sb.Append("\r\n");
            sb.Append("\r\n");

            string postHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

            // Build the trailing boundary string as a byte array
            // ensuring the boundary appears on a line by itself
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
            long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
            webrequest.ContentLength = length;

            Stream requestStream = webrequest.GetRequestStream();

            // Write out our post header
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            // Write out the file contents
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);

            // Write out the trailing boundary
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            WebResponse responce = webrequest.GetResponse();
            Stream s = responce.GetResponseStream();
            StreamReader sr = new StreamReader(s);

            return sr.ReadToEnd();
        }
    }
}
